from apps.oauth.models import ImageInfo
from config.models import Image
from routers import router
from utils.utils import json_response
from sqlalchemy.orm import sessionmaker
from config.mysql import engine

DBSession = sessionmaker(bind=engine)
db = DBSession()


@router.post("/image/add_image/", tags=['image'])
async def upload_image(image_info: ImageInfo):
    """
    上传用户头像
    :param image:
    :return:
    """
    user_image = {
        "fileKey": image_info.fileKey,
        "userId": image_info.userId
    }
    image = Image(**user_image)
    try:
        db.add(image)
        db.commit()
        db.close()
        return json_response(code=200, msg="success")
    except Exception as e:
        db.rollback()
        return json_response(code=400, msg="上传头像失败:{}".format(e))


@router.get("/image/user_image/", tags=['image'])
async def get_user_image(user_id: int):
    try:
        image = db.query(Image).filter(Image.userId==user_id).one()
        resp_data = {}
        if image:
            resp_data = {
                "id": image.id,
                "fileKey": image.fileKey,
                "createDate": image.createDate.strftime("%Y-%m-%d %H:%M:%S"),
                "updateDate": image.updateDate.strftime("%Y-%m-%d %H:%M:%S")
            }
        return json_response(code=200, msg="success", data=resp_data)
    except Exception as e:
        return json_response(code=400, msg="查询失败:{}".format(e))



